﻿using System.Collections.Generic;
using IapService.Entity;
using NHibernate.Criterion;

namespace IapService.Data
{
    public class SampleData : Data<Sample>
    {
        public new Sample Save(Sample item)
        {
            using (var session = Session)
            {
                session.SaveOrUpdate(item);
                foreach (var sampleFiller in item.SampleFillers)
                {
                    session.SaveOrUpdate(sampleFiller);
                }
                session.Flush();
            }
            return item;
        }

        public Sample SaveFavorite(Sample item)
        {
            using (var session = Session)
            {
                session.SaveOrUpdate(item);
                foreach (var sampleFiller in item.SampleFillers)
                {
                    sampleFiller.SampleId = item.Id;
                    var sampleFillerDara = new Data<SampleFiller>();
                    sampleFillerDara.Save(sampleFiller);
                }

                var favorite = new Favorite {Sample = item};
                session.SaveOrUpdate(favorite);

                session.Flush();
            }
            return item;
        }

        public Sample SaveFromFavorite(Sample item)
        {
            using (var session = Session)
            {
                session.SaveOrUpdate(item);
                foreach (var sampleFiller in item.SampleFillers)
                {
                    sampleFiller.SampleId = item.Id;
                    session.SaveOrUpdate(sampleFiller);
                }

                session.Flush();
            }
            return item;
        }

        public new Sample Remove(Sample item)
        {
            List<Favorite> favorites;
            using (var session = Session)
            {
                session.Delete(item);
                session.Flush();
                favorites = (List<Favorite>)session.CreateCriteria<Favorite>()
                                     .Add(Restrictions.Eq("Sample.Id", item.Id))
                                     .List<Favorite>();
            }
            foreach (var favorite in favorites)
            {
                var result = new FavoriteData().Remove(favorite);
            }
            return item;
        }
    }
}